<template>
  <div class="main-box">
    <!-- <el-dialog
      title="高级查询"
      :wrapper-closable="false"
      :visible.sync="drawerQuery"
      width="60%"
      :modal="false"
      :destroy-on-close="true"
    >
      <avue-form
        v-model="queryTips"
        :option="queryOption"
        @submit="querySubmit"
      />
    </el-dialog>
    <el-main>
      <div class="list-search">
        <el-button
          type="primary"
          icon="el-icon-notebook-2"
          size="small"
          @click="buildQuery"
        >
          高级查询
        </el-button>
        <el-popover
          placement="bottom"
          width="400"
          trigger="click"
          style="margin-left: 10px"
        >
          <el-checkbox-group v-model="ckData">
            <el-checkbox
              v-for="item in diyHeader"
              :key="item.prop"
              :label="item.label"
              :name="item.property"
            />
          </el-checkbox-group>
          <el-button
            slot="reference"
            type="primary"
            icon="el-icon-setting"
            size="small"
            @click="diyCloumnFlag = 2"
          >
            自定义列
          </el-button>
        </el-popover>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="small"
          style="margin-left: 10px"
          @click="refresh"
        >
          刷新
        </el-button>
      </div>
      <el-tabs
        v-model="activeName"
        class="tabBox"
        :tab-position="tabPosition"
        @tab-click="getDetail"
      >
        <el-tab-pane label="统计报表" name="1">
          <div v-for="(item, key) in quesData" :key="key" class="echart">
            <div class="title">
              Q{{ item.quesNum }} : {{ item.ques }} ({{ item.type_name }})
            </div>
            <div
              v-if="item.type != 'list'"
              :id="'echart_' + key"
              class="echartDiv"
            />
            <div v-if="item.type != 'list'">
              <el-table :data="item.detail.data" style="width: 100%">
                <el-table-column prop="name" label="选项" width="180" />
                <el-table-column prop="value" label="回复情况" width="" />
              </el-table>
            </div>
            <div v-else>
              <el-table :data="item.detail" style="width: 100%">
                <el-table-column prop="id" label="ID" width="180" />
                <el-table-column prop="answer" label="回答详情" width="" />
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据详情" name="2">
          <el-card class="box-card" style="margin-top: 10px">
            <el-table
              ref="table"
              :data="tableData"
              style="width: 100%"
              :row-style="{ height: '50px' }"
              :render-header="labelHead"
            >
              <el-table-column
                label="ID"
                prop="id"
                :show-overflow-tooltip="true"
                width="80"
              />
              <el-table-column
                v-for="item in header"
                :key="item.prop"
                :label="item.label"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.row[item.property] }}
                </template>
              </el-table-column>
              <el-table-column :label="$t('操作')" fixed="right" width="200">
                <template #default="scope">
                  <el-button
                    type="text"
                    size="small"
                    icon="el-icon-view"
                    @click="table_view(scope.row, scope.$index)"
                  >
                    查看
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="page">
              <el-pagination
                :hide-on-single-page="page.total < page.size ? true : false"
                background
                :current-page="page.currentPage"
                :page-sizes="page.pageSizes"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-main> -->
  </div>
</template>

<script>
import formApi from '@/api/form.js'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      activeName: '2',
      myChart: {},
      quesData: {},
      quesTotal: 0,
      tabPosition: 'top',
      headerData: [],
      diyHeader: [],
      diyCloumnFlag: 1,
      ckData: [],
      queryTips: {
        condition: 'and',
        childTips: [
          {
            field: '',
            rule: 'eq',
            val: ''
          }
        ]
      },
      drawerQuery: false,
      drawer: false,
      option: {},
      header: [],
      search: {
        page: 1,
        limit: 15,
        queryParams: {}
      },
      page: {
        total: 0,
        currentPage: 1,
        size: 15,
        pageSizes: [15, 25, 35, 45]
      },
      tableData: [],
      queryOption: {
        submitText: '查询',
        submitIcon: 'el-icon-search',
        labelWidth: 110,
        column: [
          {
            label: '过滤条件匹配',
            prop: 'condition',
            type: 'select',
            span: 12,
            row: true,
            dicData: [
              {
                label: 'AND（所有条件都要求匹配）',
                value: 'and'
              },
              {
                label: 'OR（条件中的任意一个匹配）',
                value: 'or'
              }
            ]
          },
          {
            label: '子表单',
            prop: 'childTips',
            type: 'dynamic',
            span: 24,
            children: {
              align: 'center',
              headerAlign: 'center',
              rowAdd: done => {
                done({
                  rule: 'eq'
                })
              },
              rowDel: (row, done) => {
                done()
              },
              column: [
                {
                  label: '字段',
                  prop: 'field',
                  type: 'select',
                  dicData: []
                },
                {
                  label: '条件',
                  prop: 'rule',
                  type: 'select',
                  dicData: [
                    {
                      label: '等于',
                      value: 'eq'
                    },
                    {
                      label: '包含',
                      value: 'like'
                    },
                    {
                      label: '以什么开始',
                      value: 'left_like'
                    },
                    {
                      label: '以什么结尾',
                      value: 'right_like'
                    },
                    {
                      label: '不等于',
                      value: 'neq'
                    },
                    {
                      label: '大于',
                      value: 'gt'
                    },
                    {
                      label: '大于等于',
                      value: 'gte'
                    },
                    {
                      label: '小于',
                      value: 'lt'
                    },
                    {
                      label: '小于等于',
                      value: 'lte'
                    }
                  ]
                },
                {
                  label: '值',
                  prop: 'val',
                  type: 'input'
                }
              ]
            }
          }
        ]
      }
    }
  },
  watch: {
    ckData(newVal, old) {
      // console.log('asdasdasd', newVal, old)
      if (this.diyCloumnFlag == 2) {
        // 减
        if (newVal.length < old.length) {
          this.header.forEach((ele, index) => {
            if (newVal.indexOf(ele.label) === -1) {
              console.log('被删的', ele.label, index)
              this.header.splice(index, 1)
            }
          })
        } else {
          // 增
          const newHeader = []
          this.diyHeader.forEach(ele => {
            if (newVal.indexOf(ele.label) !== -1) {
              newHeader.push(ele)
            }
          })

          this.header = JSON.parse(JSON.stringify(newHeader))
        }
      }
    }
  },
  created() {
    this.id = this.$route.query.id
    this.getTableInfo()
  },
  mounted() {
    this.$nextTick(() => {
      for (var i in this.myChart) {
        this.myChart[i].resize()
      }
    })
  },
  methods: {
    getDetail(e) {
      if (e.name == 1) {
        this.getLoadEcharts()
      } else {
        this.getTableInfo()
      }
    },
    async getLoadEcharts() {
      await this.getQuesDetail()

      this.showEcharts()
    },
    showEcharts() {
      for (var k in this.quesData) {
        const ele = this.quesData[k]

        if (ele.type == 'list') {
          continue
        }
        let option = {}
        if (ele.type == 'radio') {
          option = {
            xAxis: {
              type: 'category',
              data: ele.detail.nameArr
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                data: ele.detail.valueArr,
                type: 'line'
              }
            ]
          }
        }
        if (ele.type == 'checkbox') {
          option = {
            xAxis: {
              type: 'category',
              data: ele.detail.nameArr
            },
            yAxis: {
              type: 'value'
            },
            series: [
              {
                type: 'bar',
                data: ele.detail.valueArr
              }
            ]
          }
        }
        if (ele.type == 'rate') {
          option = {
            series: [
              {
                type: 'pie',
                data: ele.detail.data,
                radius: ['40%', '70%']
              }
            ]
          }
        }

        // 基于准备好的dom，初始化echarts实例
        if (!this.myChart[k]) {
          this.myChart[k] = echarts.init(document.getElementById('echart_' + k))
        }
        // 绘制图表
        this.myChart[k].setOption(option, true)
      }

      window.addEventListener('resize', () => {
        for (var i in this.myChart) {
          this.myChart[i].resize()
        }
      })
    },
    searchSuccess() {
      this.getTableInfo()
      this.getLoadEcharts()
    },
    labelHead(h, { column, index }) {
      // 动态表头渲染
      return h('span', { class: 'table-head', style: { width: '100%' } }, [
        column.label
      ])
    },
    // 查询构建器
    async querySubmit(form, done) {
      this.search.queryParams = this.queryTips
      this.getTableInfo()
      this.getLoadEcharts()
      this.drawerQuery = false
      done()
    },
    async getQuesDetail() {
      this.search.id = this.id
      const res = await formApi.quesDetail(this.search)
      this.header = JSON.parse(JSON.stringify(res.data.header))
      this.headerData = this.header
      this.quesData = res.data.data
      this.quesTotal = res.data.total

      this.queryOption.column[1].children.column[0].dicData = []

      for (var i in res.data.header) {
        const ele = res.data.header[i]
        this.ckData.push(ele.label)
        // 拼装自定义查询的字段部分
        this.queryOption.column[1].children.column[0].dicData.push({
          label: ele.label,
          value: ele.property
        })
      }
      this.diyHeader = JSON.parse(JSON.stringify(res.data.header))
    },
    async getTableInfo() {
      this.search.id = this.id
      const res = await formApi.detail(this.search)
      this.header = JSON.parse(JSON.stringify(res.data.header))
      this.headerData = this.header
      this.tableData = res.data.data
      this.page.total = res.data.total

      this.queryOption.column[1].children.column[0].dicData = []
      res.data.header.forEach(ele => {
        this.ckData.push(ele.label)
        // 拼装自定义查询的字段部分
        this.queryOption.column[1].children.column[0].dicData.push({
          label: ele.label,
          value: ele.property
        })
      })

      this.diyHeader = JSON.parse(JSON.stringify(res.data.header))
    },
    async getDiyForm() {
      const res = await this.$api.diy.form.get({ id: this.id })
      this.option = res.data
      this.option.filterDic = true

      if (this.mode == 'view') {
        this.option.detail = true
      }
    },
    // 刷新
    refresh() {
      this.search.queryParams = {}
      this.getTableInfo()
    },
    // 重置查询条件
    resetQuery() {
      this.queryTips = {
        condition: 'and',
        childTips: [
          {
            field: '',
            rule: 'eq',
            val: ''
          }
        ]
      }
    },
    // 查询构建器
    buildQuery() {
      this.resetQuery()
      this.drawerQuery = true
      this.queryOption.filterDic = true
    },
    // 查看
    async table_view(row, index) {
      this.mode = 'view'
      // this.getDiyForm()
      this.drawerQuery = true

      this.nowRowId = row.id
      const res = await formApi.formInfo({
        form_id: this.id,
        table_id: row.id
      })
      this.queryTips = res.data
      this.form = res.data
    },
    // 分页规格改变
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.search.page = 1
      this.search.limit = val
      this.getList()
    },
    // 分页点击
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.search.page = val
      this.search.limit = this.page.size
      this.getList()
    }
  }
}
</script>

<style scoped lang="scss">
.el-checkbox {
  width: 80px;
}
#app .avue-form {
  /* display: none; */
}
#app .avue-form >>> .el-button--mini {
  padding: 6px;
}
#app .avue-form >>> .el-table__fixed-right::before,
#app .avue-form >>> .el-table__fixed::before {
  height: 0;
}
.tabBox {
  padding: 30px;
  width: 100%;
  min-height: 300px;
}
.tabBox .title {
  padding: 10px 0;
}
.tabBox .box-card {
  margin: 0;
}

.tabBox .el-table__fixed-right::before,
.tabBox .el-table__fixed::before {
  height: 0;
}

.echart {
  width: 100%;
  height: 100%;
  padding-bottom: 30px;
}
.echartDiv {
  width: 600px;
  height: 300px;
  margin: 0 auto;
}
</style>
